import { fabric } from 'fabric';

class Text extends fabric.IText {
  constructor(options = {}) {
    const defaultOptions = {
      left: 100,
      top: 100,
      width: 300,
      text: '双击编辑文本',
      fontSize: 20,
      fontFamily: 'Arial',
      fill: '#333333',
      strokeWidth: 0,
      textAlign: 'left',
      editingBorderColor: '#1890ff',
      cursorColor: '#1890ff',
      cursorWidth: 2,
      cornerColor: '#1890ff',
      cornerSize: 10,
      transparentCorners: false,
      hasRotatingPoint: true,
      padding: 5,
      editable: true,
      selectable: true,
      id: '',  // 添加id属性
    };

    // 合并默认选项和传入的选项
    const mergedOptions = {
      ...defaultOptions,
      ...options,
    };

    super(mergedOptions.text, mergedOptions);

    // 如果提供了canvas，自动添加到画布
    if (options.canvas) {
      options.canvas.add(this);
      options.canvas.requestRenderAll();
    }

    // 初始化样式对象
    this.styles = this.styles || {};

    // 监听文本编辑事件
    this.on('editing:entered', () => {
      console.log('Editing entered');
      this.isEditing = true;
      if (this.canvas && typeof this.canvas.getRetinaScaling === 'function') {
        this.canvas.requestRenderAll();
      }
    });

    this.on('editing:exited', () => {
      console.log('Editing exited');
      this.isEditing = false;
      if (this.canvas && typeof this.canvas.getRetinaScaling === 'function') {
        this.canvas.requestRenderAll();
      }
    });

    // 监听选择变化
    this.on('selection:changed', () => {
      console.log('Selection changed', this.selectionStart, this.selectionEnd);
      this.canvas?.requestRenderAll();
    });
  }

  // 更新属性
  updateProps(props) {
    console.log('Text.updateProps called with:', props);
    console.log('Is editing:', this.isEditing);
    if (!this.canvas || typeof this.canvas.getRetinaScaling !== 'function') {
      console.warn('Canvas not available or missing getRetinaScaling method');
      return this;
    }
    console.log('Selection:', this.selectionStart, this.selectionEnd);

    // 如果正在编辑且有选中的文本，则只更新选中文本的样式
    if (this.isEditing && this.selectionStart !== this.selectionEnd) {
      console.log('Updating selected text styles');

      try {
        // 获取当前行和选择范围
        const startLine = this.get2DCursorLocation(this.selectionStart).lineIndex;
        const endLine = this.get2DCursorLocation(this.selectionEnd).lineIndex;
        const startChar = this.get2DCursorLocation(this.selectionStart).charIndex;
        const endChar = this.get2DCursorLocation(this.selectionEnd).charIndex;

        console.log('Lines:', startLine, endLine);
        console.log('Chars:', startChar, endChar);

        // 确保styles对象存在
        if (!this.styles) {
          this.styles = {};
        }

        // 为每一行应用样式
        for (let lineIndex = startLine; lineIndex <= endLine; lineIndex++) {
          if (!this.styles[lineIndex]) {
            this.styles[lineIndex] = {};
          }

          // 确定当前行的起始和结束字符索引
          const lineStartChar = lineIndex === startLine ? startChar : 0;
          const lineEndChar = lineIndex === endLine ? endChar : this._textLines[lineIndex].length;

          console.log(
            `Applying styles to line ${lineIndex}, chars ${lineStartChar}-${lineEndChar}`,
          );

          // 为每个字符应用样式
          for (let charIndex = lineStartChar; charIndex < lineEndChar; charIndex++) {
            if (!this.styles[lineIndex][charIndex]) {
              this.styles[lineIndex][charIndex] = {};
            }

            // 应用样式属性
            if (props.fontFamily) this.styles[lineIndex][charIndex].fontFamily = props.fontFamily;
            if (props.fontSize) this.styles[lineIndex][charIndex].fontSize = props.fontSize;
            if (props.fill) this.styles[lineIndex][charIndex].fill = props.fill;
            if (props.backgroundColor)
              this.styles[lineIndex][charIndex].textBackgroundColor = props.backgroundColor;
            if (props.fontWeight) this.styles[lineIndex][charIndex].fontWeight = props.fontWeight;
            if (props.fontStyle) this.styles[lineIndex][charIndex].fontStyle = props.fontStyle;
            if (props.underline) this.styles[lineIndex][charIndex].underline = props.underline;
            if (props.linethrough)
              this.styles[lineIndex][charIndex].linethrough = props.linethrough;
          }
        }

        console.log('Updated styles:', JSON.stringify(this.styles));

        // 标记为脏以便重新渲染
        this.dirty = true;
      } catch (error) {
        console.error('Error updating text styles:', error);
      }
    } else {
      // 否则更新整个文本对象的样式
      console.log('Updating whole text styles');
      this.set(props);
      // 如果更新了边框颜色，同时更新控制点颜色
      if (props.stroke) {
        this.set({
          cornerColor: props.stroke,
          borderColor: props.stroke,
        });
      }
    }
  }

  // 获取选中文本的样式
  getSelectedTextStyles() {
    if (!this.isEditing || this.selectionStart === this.selectionEnd) {
      return null;
    }

    const lineIndex = this.get2DCursorLocation(this.selectionStart).lineIndex;
    const charIndex = this.get2DCursorLocation(this.selectionStart).charIndex;

    // 返回选中文本的第一个字符的样式
    return this.styles && this.styles[lineIndex] && this.styles[lineIndex][charIndex]
      ? this.styles[lineIndex][charIndex]
      : null;
  }

  // 置顶
  bringToFront() {
    if (this.canvas) {
      this.canvas.bringToFront(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 置底
  sendToBack() {
    if (this.canvas) {
      this.canvas.sendToBack(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }

  // 移除
  remove() {
    if (this.canvas) {
      this.canvas.remove(this);
      this.canvas.requestRenderAll();
    }
    return this;
  }
}

export default Text;
